import { localCache } from '@/utils/cache'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from "@/router";

export const request = (options: any) => {
  return new Promise((resolve, reject) => {
    const service = axios.create({
      baseURL: import.meta.env.VITE_BASE_URL,
      timeout: 30 * 1000
    })

    service.interceptors.request.use(
      (config: any) => {
        const token: string = localCache.getCache('myToken')
        if (token) {
          config.headers['Authorization'] = token
        }
        return config
      },
      (error) => {
        Promise.reject(error)
      }
    )

    service.interceptors.response.use(
      (response: any) => {
        if (response.data.code == 200) {
          return Promise.resolve(response.data)
        } else if (response.data.code == 401) {
          ElMessage.error('登录已过期，请重新登录')
          localCache.clearCache()
          router.push('/login')
        } else if (response.data.code) {
          ElMessage.error(response.data.msg)
          return Promise.reject(response.data)
        } else {
          // 文件
          return Promise.resolve(response)
        }
      },
      (error) => {
        console.log('err' + error)
        if (error.response.status == 403) {
          ElMessage.error('暂无权限')
        } else {
          ElMessage.error('服务器请求错误，请稍后再试')
        }
        return Promise.reject(error)
      }
    )
    // 请求处理
    service(options)
      .then((res) => {
        resolve(res)
      })
      .catch((error) => {
        reject(error)
      })
  })
}

export default request
